﻿// Copyright (c) 2012, Alexander Endris
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

#endregion

namespace NamelessOne.Imaging.Png
{
  /// <summary>
  ///   Represents a file stream that automatically advances its underlying position to the next iDat chunk
  /// </summary>
  internal class IDatStream : FileStream
  {
    #region Public / Constructors

    /// <summary>
    ///   Creates the IDatStream
    /// </summary>
    /// <param name = "path">Full path to the file</param>
    /// <param name = "mode">File Mode</param>
    /// <param name = "iDatOffsets">IDat offsets</param>
    /// <param name = "iDatLengths">IDat lengths</param>
    public IDatStream(string path, FileMode mode) : base(path, mode)
    {
      base.Seek(8, SeekOrigin.Begin);
      SeekToNextIDat();
      base.Seek(2, SeekOrigin.Current);
    }

    #endregion

    #region Public / Methods

    public override int Read(byte[] array, int offset, int count)
    {
      long iDatOffset = currentOffset;
      long length = currentLength;

      long boundary = iDatOffset + length;
      int possibleCount = (int) (boundary - Position);

      bool advance = false;
      if (count > possibleCount)
      {
        count = possibleCount;
        advance = true;
      }

      int bytesRead = base.Read(array, offset, count);

      if (advance)
      {
        //Skip CRC
        base.Seek(4, SeekOrigin.Current);
        SeekToNextIDat();
      }

      return bytesRead;
    }

    #endregion

    #region Private / Attributes

    private static readonly uint IDatChunk = 0x49444154;
    private static readonly uint IEndChunk = 0x49454e44;
    private long currentLength;
    private long currentOffset;

    private readonly List<uint> iDatLengths;
    private readonly List<long> iDatOffsets;

    #endregion

    #region Private / Methods

    private uint ReadUInt32()
    {
      byte[] bytes = new byte[4];
      base.Read(bytes, 0, 4);

      return (uint) IPAddress.HostToNetworkOrder(BitConverter.ToInt32(bytes, 0));
    }

    private bool SeekToNextIDat()
    {
      uint chunkSize = ReadUInt32();
      uint chunkType = ReadUInt32();
      while (chunkType != IEndChunk)
      {
        if (chunkType == IDatChunk)
        {
          currentOffset = Position;
          currentLength = chunkSize;
          return true;
        }
        Seek(chunkSize + 4, SeekOrigin.Current);
        chunkSize = ReadUInt32();
        chunkType = ReadUInt32();
      }
      return false;
    }

    #endregion
  }
}